import { defineStore } from 'pinia'
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from '../utils'
import { getUserInfo } from '@/api/user'
import { getSession, refreshTokenApi, logout } from '@/api/session'
import { useMultiTagsStoreHook } from './multiTags'
import {
  type UserInfo,
  setToken,
  removeToken,
  userKey,
  setUserInfo
} from '@/utils/auth'
import { HttpResultCode } from '@/utils/http/enums'
import { message } from '@/utils/message'

export const useUserStore = defineStore({
  id: 'pure-user',
  state: (): userType => ({
    id: storageLocal().getItem<UserInfo>(userKey)?.id ?? 0,
    // 头像
    avatar: storageLocal().getItem<UserInfo>(userKey)?.avatar ?? '',
    // 用户名
    username: storageLocal().getItem<UserInfo>(userKey)?.username ?? '',
    // 昵称
    nickname: storageLocal().getItem<UserInfo>(userKey)?.nickname ?? '',
    // 页面级别权限
    roles: storageLocal().getItem<UserInfo>(userKey)?.roles ?? [],
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7
  }),
  actions: {
    /** 存储ID */
    SET_ID(id: number) {
      this.id = id
    },
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username
    },
    /** 存储昵称 */
    SET_NICKNAME(nickname: string) {
      this.nickname = nickname
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value)
    },
    /** 登入 */
    async loginByUsername(data) {
      const { code, msg, data: sessionInfo } = await getSession(data)
      if (code !== HttpResultCode.Success) {
        message(msg, { type: 'error' })
        return Promise.reject('登录失败')
      }
      const token = {
        ...sessionInfo,
        expires: sessionInfo.expiresIn
      }
      setToken(token)
      await this.getUserInfo()
    },
    async getUserInfo() {
      const { code, data } = await getUserInfo()
      if (code !== HttpResultCode.Success) {
        message('获取用户信息失败', { type: 'error' })
        return Promise.reject('获取用户信息失败')
      }
      const userRes = {
        ...data,
        roles: data.auth === 99 ? ['admin'] : ['common']
      }
      setUserInfo(userRes)
      return userRes
    },
    /** 前端登出（不调用接口） */
    logOut() {
      logout()
      this.username = ''
      this.roles = []
      removeToken()
      useMultiTagsStoreHook().handleTags('equal', [...routerArrays])
      resetRouter()
      router.push('/login')
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      // return new Promise<RefreshTokenResult>((resolve, reject) => {
      //   refreshTokenApi(data)
      //     .then(data => {
      //       if (data) {
      //         setToken(data.data)
      //         resolve(data)
      //       }
      //     })
      //     .catch(error => {
      //       reject(error)
      //     })
      // })
      const { code, data: sessionInfo } = await refreshTokenApi(data)
      if (code !== HttpResultCode.Success) {
        return Promise.reject('刷新Token失败')
      }
      const userRes = {
        ...sessionInfo,
        expires: sessionInfo.expiresIn
      }
      setToken(userRes)
      return userRes
    }
  }
})

export function useUserStoreHook() {
  return useUserStore(store)
}
